<?php
/**
 * 前置端口
 */
namespace Common\Controller;

use Think\Controller;
use Org\Util\Wechat;
use Manage\Model\MemberModel;




class ActionController extends Controller
{
	protected $user			=	'';		//存放用户信息
	private $_isWeixin		=	0;		//微信浏览器访问标识
    private $_openid 		= '';		//关注用户微信openid
    private $_headimgurl 	= '';		//关注用户微信头像
    private $_nickname 		= '';		//关注用户微信昵称
    private $_subscribe		= '';		//关注用户微信关注状态
	
	public function __construct()
	{
		parent::__construct();
		//初始化 登陆模块
		$this->init();
	}

	public function init()
	{
		// 初始化登陆状态
		$this->checklogin();
		if(!$this->user['user_id']){
			$hostUrl	=	"http://".$_SERVER['HTTP_HOST']."/manage/user/login";
			redirect($hostUrl);
			//$this->redirect('manage/user/login');
		}
		
	}
	
	/**
     * 获取用户登录信息 无则为空
     */	
	public function checklogin()
	{
		return $this->user = getAuth('all');
	}
		
	/**
     * 创建Wechat对象
     */
    protected function createWechatObj()
	{
        $options = array(
            'token'		=> C('WX_TOKEN'), //填写你设定的key
            'appid'		=> C('WX_APPID'), //填写高级调用功能的app id
            'appsecret'	=> C('WX_APPSECRET') //填写高级调用功能的密钥
        );
        return new Wechat($options);
    }
	
	/**
     * 微信OAuth2.0授权
     * 授权成功并获取微信用户信息,openid、关注情况、微信用户头像将被保存在cookie中。
     *
     * @param string $scope 应用授权作用域(snsapi_base,snsapi_userinfo)
     */
    protected function wechatOAuth2($scope = 'snsapi_base')
	{
        if($this->_openid){
            return;
        }
        $this->wechat = $this->createWechatObj();
        if(isset($_GET['code']) && isset($_GET['state'])){
            //通过code换取网页授权access_token
            $access_token = $this->wechat->getOauthAccessToken();
            if(empty($access_token)){
                exit('获取access_token失败!('.$this->wechat->errCode.')');
            }
            //获取用户信息
            if(strpos($access_token['scope'], 'snsapi_userinfo') === FALSE){
                $user_info = $this->wechat->getUserInfo($access_token['openid']);
                if(empty($user_info)){
                    exit('获取用户信息失败!('.$this->wechat->errCode.')');
                }
                if($user_info['subscribe'] == 0 || $user_info['openid'] == 'ocv__jq6QNPiLjP_VkACxR-p4SRo'){
                    $this->wechatAuthorize('snsapi_userinfo');
                }
            }else{
                $user_info = $this->wechat->getOauthUserinfo($access_token['access_token'], $access_token['openid']);
                if(empty($user_info)){
                    exit('获取用户信息失败!('.$this->wechat->errCode.')');
                }
            }
            $this->_openid 		= $access_token['openid'];
            $this->_headimgurl 	= $user_info['headimgurl'];
            $this->_subscribe 	= isset($user_info['subscribe']) ? 1 : 0;
            //过滤掉非UTF-8字符,解决用户使用emoji表情作为昵称无法保存的问题。
            $user_info['nickname'] = preg_replace("#\\\u([0-9a-f]+)#ie", 
                "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $user_info['nickname']);
            $this->_nickname = $user_info['nickname'];
            addCookie('openid', $this->_openid, 0);
            // addCookie('headimgurl', $user_info['headimgurl'], 0);
            // addCookie('nickname', $user_info['nickname'], 0);
            // addCookie('subscribe', isset($user_info['subscribe']) ? 1 : 0, 0);
        }else{
            $this->wechatAuthorize($scope);
        }
    }
	
	  /**
     * 发起授权获取code
     *
     * @param string $scope 应用授权作用域
     */
    protected function wechatAuthorize($scope){
        $request_uri = $_SERVER['REQUEST_URI'];
        if(strpos($_SERVER['REQUEST_URI'], 'code')){
            $code_pos = strpos($_SERVER['REQUEST_URI'], 'code');
            $request_uri = rtrim(substr($_SERVER['REQUEST_URI'], 0, $code_pos), '&');
        }
        $callback = C('SITE_DOMAIN').ltrim($request_uri, '/');
        $redirect_uri = $this->wechat->getOauthRedirect($callback, '123', $scope);
        header('Location:'.$redirect_uri);
        exit;
    }
	
	 /**
     * 是否为微信访问
     */
    protected function setIsWeixin()
	{
        if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") !== FALSE){
            $this->_isWeixin	= 1;
        }else{
            $this->_isWeixin 	= 0;
        }
    }
}
